package com.ad.platform.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 日期工具类
 * @author phu
 * 2015-12-16
 */
public class DateUtil {
    private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");

    private final static SimpleDateFormat sdfDay = new SimpleDateFormat(
            "yyyy-MM-dd");

    private final static SimpleDateFormat sdfDay2 = new SimpleDateFormat(
            "yyyy-M-d");

    private final static SimpleDateFormat sdfDays = new SimpleDateFormat(
            "yyyyMMdd");

    private final static SimpleDateFormat sdfMonth = new SimpleDateFormat(
            "MM");

    private final static SimpleDateFormat sdfTime = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    private final static SimpleDateFormat sdfTime2 = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm");

    private final static String sdfTimeStr = "yyyy-MM-dd HH:mm:ss";

    private final static String sdfTimeStr2 = "yyyy-MM-dd HH:mm";



    /**
     * 获取指定时间的时间戳
     * */
    public static Long getDateTimeForMin(String date){
        Date parse = null;
        try {
            parse = sdfTime2.parse(date);
            String s = DateUtil.fomatDateTime(parse);
            System.out.println(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse.getTime();
    }



    /**
     * 获取yyyy-MM-dd
     */
    public static String formatYmd(Date d) {
        return sdfDay.format(d);
    }

    /**
     * 获取yyyyMMdd
     */
    public static String formatYmd2(Date d) {
        return sdfDays.format(d);
    }

    /**
     * 获取YYYY格式
     *
     * @return
     */
    public static String getYear() {
        return sdfYear.format(new Date());
    }


    /**
     * 获取月份
     *
     * @return
     */
    public static String formatMonth(Date d) {
        return sdfMonth.format(d);
    }


    /**
     * 获取YYYY格式
     *
     * @return
     */
    public static String formatYear(Date d) {
        return sdfYear.format(d);
    }


    /**
     * 获取当前月
     *
     * @return
     */
    public static String getMonth() {
        return new SimpleDateFormat("MM").format(new Date());
    }

    /***
     * 获取当前天
     * @return
     */
    public static String getCurrentDay() {
        return new SimpleDateFormat("dd").format(new Date());
    }

    /**
     * 获取YYYY-MM-DD格式
     *
     * @return
     */
    public static String getDay() {
        return sdfDay.format(new Date());
    }

    /**
     * 获取YYYY-MM-DD格式
     *
     * @return
     */
    public static String getDay(Date date) {
        if (date == null) {
            date = new Date();
        }
        return sdfDay.format(date);
    }

    /**
     * 获取YYYY-MM-DD HH:mm格式
     *
     * @return
     */
    public static String getSdfTime2(Date date) {
        if (date == null) {
            date = new Date();
        }
        return sdfTime2.format(date);
    }

    /**
     * 获取YYYY-M-D格式
     *
     * @return
     */
    public static String getDay2(Date date) {
        if (date == null) {
            date = new Date();
        }
        return sdfDay2.format(date);
    }

    /**
     * 获取YYYYMMDD格式
     *
     * @return
     */
    public static String getDays() {
        return sdfDays.format(new Date());
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     *
     * @return
     */
    public static String getTime() {
        return sdfTime.format(new Date());
    }

    /**
     * 获取系统时间（格式：YYYY-MM-DD HH:mm）
     *
     * @return
     */
    public static String getTime2() {
        return sdfTime.format(new Date()).substring(0, 16);
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     *
     * @return
     */
    public static String getTime(Date dt) {
        if (dt == null) {
            dt = new Date();
        }
        return sdfTime.format(dt);
    }

    /**
     * 获取YYYY-MM-DD HH:mm格式
     *
     * @return
     */
    public static String getTime2(Date dt) {
        if (dt == null) {
            dt = new Date();
        }
        String time = sdfTime.format(dt);
        if (time != null && time != "" && time.length() == sdfTimeStr.length()) {
            time = time.substring(0, 16);
        }
        return time;
    }


    /**
     * @param s
     * @param e
     * @return boolean
     * @throws
     * @Title: compareDate
     * @Description: TODO(日期比较 ， 如果s > = e 返回true 否则返回false)
     * @author luguosui
     */
    public static boolean compareDate(String s, String e) {
        if (fomatDate(s) == null || fomatDate(e) == null) {
            return false;
        }
        return fomatDate(s).getTime() >= fomatDate(e).getTime();
    }

    /**
     * 时间比较（yyyy-MM-dd HH:mm:ss）
     *
     * @param s
     * @param e
     * @return boolean
     * @throws
     * @Title: compareTime
     * @Description: TODO(日期比较 ， 如果s > = e 返回true 否则返回false)
     * @author
     */
    public static boolean compareTime(String s, String e) {
        if (fomatDateTime(s) == null || fomatDateTime(e) == null) {
            return false;
        }
        return fomatDateTime(s).getTime() >= fomatDateTime(e).getTime();
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static Date fomatDate(String date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static String fomatDate(Date date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return fmt.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static Date fomatDate_(Date date) {
        try {
            return fomatDate(fomatDate(date));
        } catch (Exception e) {
            e.printStackTrace();
            return new Date();
        }
    }

    /**
     * 格式化日期时间
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static Date fomatDateTime(String date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验日期是否合法
     *
     * @return
     */
    public static boolean isValidDate(String s) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            fmt.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    /**
     * 校验日期是否合法
     *
     * @return
     */
    public static boolean verifyDate(String s) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            fmt.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    public static int getDiffYear(String startTime, String endTime) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            long aa = 0;
            int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
            return years;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return 0;
        }
    }

    /**
     * <li>功能描述：时间相减得到天数
     *
     * @param beginDateStr 开始日期
     * @param endDateStr   结束日期
     * @return long
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr, String endDateStr) {
        long day = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;

        try {
            beginDate = format.parse(beginDateStr);
            endDate = format.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        //System.out.println("相隔的天数="+day);

        return day;
    }

    /**
     * <li>功能描述：时间相减得到分钟数
     *
     * @param beginDateStr
     * @param endDateStr
     * @return long
     * @author Administrator
     */
    public static long getMinuteSub(String beginDateStr, String endDateStr) {
        long minute = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date beginDate = null;
        Date endDate = null;

        try {
            beginDate = format.parse(beginDateStr);
            endDate = format.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        minute = (endDate.getTime() - beginDate.getTime()) / (60 * 1000);

        return minute;
    }

    /**
     * 得到n天之后的日期
     *
     * @param days
     * @return
     */
    public static String getAfterDayDate(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdfd.format(date);

        return dateStr;
    }

    /**
     * 得到当前传入时间n天之后的日期
     *
     * @param days
     * @return
     */
    public static Date getDateAfterDayDate(Date date, String days) {
        int daysInt = Integer.parseInt(days);

        // java.util包
        Calendar canlendar = Calendar.getInstance();
        canlendar.setTime(date);
        // 日期减 如果不够减会将月变动
        canlendar.add(Calendar.DATE, daysInt);
        Date time = canlendar.getTime();
        return time;
    }


    /**
     * 得到n天之后是周几
     *
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(date);

        return dateStr;
    }

    /**
     * 得到某个日期n天之后的日期
     *
     * @param days
     * @return
     */
    public static Date getAfterDayDate(Date date, String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.setTime(date);
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动

        return canlendar.getTime();
    }

    /**
     * 得到n个小时之后的时间
     *
     * @param hour
     * @return
     */
    public static Date getAfterHourDate(String hour) {
        int daysInt = Integer.parseInt(hour);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        // canlendar.setTime(date);
        canlendar.add(Calendar.HOUR, daysInt); // 日期减 如果不够减会将天变动

        return canlendar.getTime();
    }

    /**
     * 得到某一日期是星期几
     *
     * @param datestr
     * @return
     */
    public static int getWeekOfDate(String datestr) {
        Calendar canlendar = Calendar.getInstance();
        canlendar.setTime(fomatDate(datestr));
        return canlendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 得到某个年份的上一年
     *
     * @param year
     * @return
     */
    public static String getAfterUpYear(String year) {
        Calendar canlendar = Calendar.getInstance(); // java.util包
        Date date;
        if (year == null || "".equals(year) || !isValidDate(year + "-01-01")) {
            date = new Date();
        } else {
            date = fomatDate(year + "-01-01");
        }
        canlendar.setTime(date);
        canlendar.add(Calendar.YEAR, -1);
        return String.valueOf(canlendar.get(Calendar.YEAR));
    }

    /**
     * 得到某个月的上一月第一天的日期（YYYY-MM-DD）
     *
     * @param monthDate
     * @return
     */
    public static String getAfterMonthDate(String monthDate) {
        Calendar canlendar = Calendar.getInstance(); // java.util包
        Date date;
        if (monthDate == null || "".equals(monthDate) || !isValidDate(monthDate + "-01")) {
            date = new Date();
        } else {
            date = fomatDate(monthDate + "-01");
        }
        canlendar.setTime(date);
        canlendar.add(Calendar.MONTH, -1);
        return sdfDay.format(canlendar.getTime());
    }

    /**
     * 得到某个月的最后一天（YYYY-MM-DD）
     *
     * @param monthDate
     * @return
     */
    public static String getMonthEndDate(String monthDate) {
        Calendar canlendar = Calendar.getInstance(); // java.util包
        Date date;
        if (monthDate == null || "".equals(monthDate) || !isValidDate(monthDate + "-01")) {
            date = new Date();
        } else {
            date = fomatDate(monthDate + "-01");
        }
        canlendar.setTime(date);
        canlendar.add(Calendar.MONTH, 1);
        canlendar.add(Calendar.DATE, -1);
        return sdfDay.format(canlendar.getTime());
    }

    /**
     * 获取日期的月份-日期
     *
     * @return
     */
    public static String getMonthDate(Date date) {
        return new SimpleDateFormat("M-d").format(date);
    }

    /**
     * 获取日期的月份
     *
     * @return
     */
    public static String getMonth(String date) {
        return new SimpleDateFormat("MM").format(fomatDate(date));
    }

    /**
     * 获取日期的年份
     *
     * @return
     */
    public static String getYear(String date) {
        return new SimpleDateFormat("YYYY").format(fomatDate(date));
    }


    /**
     * 格式化日期时间（Object to String）
     *
     * @return yyyy-MM-dd HH:mm
     */
    public static String fomatDateTime(Object value) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return value == null ? "" : fmt.format(value);
    }

    /**
     * 格式化日期时间（[yyyy-MM-dd HH:mm:ss] to [yyyy-MM-dd HH:mm]）
     *
     * @return yyyy-MM-dd HH:mm
     */
    public static String fomatDateTime2(Object value) {
        String dateStr = "";
        if (value != null && sdfTimeStr2.length() < value.toString().length()) {
            dateStr = value.toString().substring(0, sdfTimeStr2.length());
        } else {
            dateStr = value == null ? "" : value.toString();
        }
        return dateStr;
    }

    /**
     * 格式化日期时间
     *
     * @return yyyy-MM-dd 异常时，返回空串
     */
    public static String fomatDate2(Object value) {
        try {
            return value == null ? "" : sdfDay.format(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s) {
        try {
            if (StringUtils.isBlank(s) || Objects.equals(s, 0)) return "";
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long lt = new Long(s);
            Date date = new Date(lt);
            res = simpleDateFormat.format(date);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 得到某个时间n天前的时间
     *
     * @param date 时间
     * @param num  天数
     * @return
     */
    public static Date getADayEarlier(Date date, int num) {
        Calendar cal = Calendar.getInstance();
        //设置起时间
        cal.setTime(date);
        //减n天  
        cal.add(Calendar.DATE, -num);
        return cal.getTime();
    }

    /**
     * 格式化日期时间，精确到分钟
     *
     * @return yyyy-MM-dd HH:mm
     */
    public static Date fomatDateTimeMM(String date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(Long s) {
        try {
            if (Objects.equals(s, null) || s == 0) return "";
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(s);
            res = simpleDateFormat.format(date);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 月份相加
     * */
    public static String monthAdd(Date d, Integer addMonth){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(d);
        gc.add(2, addMonth);//2代表月份，1代表在当前的日期添加一个月
        gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE));
        String timeString = sf.format(gc.getTime());
        return timeString;
    }

    /**判断日期是否是今天*/
    public static boolean isThisTime(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }


    /**
     * 根据年 月 获取对应的月份 天数
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }


    public static Map<String, Object> getMonthEveryDays(String date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> map = new LinkedHashMap<>();
        try {
            Date parse = simpleDateFormat.parse(date);
            int year = Integer.valueOf(getYear(fomatDate(parse)));
            int month = Integer.valueOf(getMonth(fomatDate(parse)));
            Integer num = getDaysByYearMonth(year, month);
            for (int i = 1; i <= num; i++) {
                map.put(month+"-"+i, i);
            }
            return map;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null ;
    }



}